import {Inject, Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class TorrentService {

  constructor(private http: HttpClient, @Inject('BASE_CONFIG') private config) {
  }

  upload(torrent: any, token: string): Observable<any> {
    const url = `${this.config.baseUrl}/torrent`;
    const formData = new FormData();
    formData.append('torrent', torrent);
    return this.http.post<any>(url, formData, {
      headers: {
        token
      }
    });
  }

  // downloadToClient(id: number, userToken: string, sessionId = '') {
  //   const url = `${this.config.baseUrl}/torrent/download/${id}/${userToken}`;
  //   const clientUrl = 'http://tr.zzyitj.xyz:11000/transmission/rpc';
  //   const auth = 'Basic ' + btoa('zzyandzzy:zzyianzhi1128');
  //   console.log(auth);
  //   const data = {
  //     method: 'torrent-add',
  //     arguments: {
  //       metainfo: '',
  //       filename: url,
  //       'download-dir': '/volume2/pt/study',
  //       paused: true
  //     },
  //     tag: ''
  //   };
  // this.http.post(clientUrl, data, {
  //   observe: 'response',
  //   headers: {
  //     'Content-Type': 'application/json',
  //     Authorization: auth,
  //     'X-Transmission-Session-Id': sessionId
  //   }
  // }).subscribe(resp => {
  //   console.log(resp);
  //   if (resp.status === 409) {
  //     this.downloadToClient(id, userToken, resp.headers.get('X-Transmission-Session-Id'));
  //   } else if (resp.status === 200) {
  //     console.log('success');
  //   }
  // });
  // }

  download(tid: number, token: string): Observable<any> {
    const url = `${this.config.baseUrl}/torrent/${tid}/${token}`;
    return this.http.get(url, {
      responseType: 'arraybuffer',
      observe: 'response'
    });
  }
}
